<template>
  <div class="app-container">
    <!-- 计划申报 -->
    <el-card shadow="hover" header="计划申报" class="flex1 h" v-loading="planLoading">
      <template #header>
        <div class="disf jub alc">
          计划申报
          <div v-if="isAudit">
            <el-button type="success" @click="handleApprove(true)">通 过</el-button>
            <el-button type="danger" @click="handleApprove(false)">驳 回</el-button>
          </div>
        </div>
      </template>
      <div class="disf dirc h pr30">
        <el-form label-width="100px">
          <el-form-item label="合同名称" prop="name">{{ name }}</el-form-item>
          <el-form-item label="项目流程"></el-form-item>
        </el-form>
        <el-scrollbar always class="flex1 ml30" v-if="activityId">
          <div class="flow-node-wrap" v-loading="flowLoading">
            <!-- 遍历：节点列表 -->
            <template v-for="(node, idx) in nodeList" :key="node.id">
              <div class="flow-node">
                <!-- 节点名称 -->
                <div class="node-name">
                  <div class="node-index ml25">{{ idx + 1 }}</div>
                  <div class="disf dirc flex1 w0 plr15">
                    <b>{{ node.name }}</b>
                    <span class="node-remark" :title="node.remark">
                      {{ node.remark || "暂无描述" }}
                    </span>
                  </div>
                  <el-tag type="primary" effect="plain" class="node-tag mr15">
                    {{ FLOW_NODE_TYPE_LABEL[node.nodeType] }}
                    <el-tooltip v-if="node.nodeType == FlowNodeType.AUDITOR_NODE" :content="getAuditBackName(node)"
                      placement="top">
                      <el-icon style="cursor: pointer">
                        <QuestionFilled />
                      </el-icon>
                    </el-tooltip>
                  </el-tag>
                </div>
                <!-- 节点任务列表 -->
                <ol class="node-tasks">
                  <li class="task-line" v-for="task in node.tasks">
                    <div class="task-title">
                      <b>{{ task.name }}</b>
                      <span class="role-icon">
                        <el-icon class="mr5">
                          <User />
                        </el-icon>
                        {{ FLOW_ACT_ROLE_LABEL[task.activityRole] }}
                      </span>
                    </div>
                    <div class="task-remark" :title="task.remark">
                      <span>{{ task.remark }}</span>
                    </div>
                    <div class="task-remark disf alc">
                      <el-icon class="mr5">
                        <Postcard />
                      </el-icon>
                      {{ FLOW_CANDIDAT_TYPE_LABEL[task.candidateType] }}【{{ task.candidateName }}】
                    </div>
                    <div class="task-remark disf alc juend">
                      <el-button size="small" link icon="warning" type="primary" @click="handleDtlTask(task.id)">
                        详情
                      </el-button>
                    </div>
                  </li>
                </ol>
              </div>
            </template>
          </div>
        </el-scrollbar>
        <el-empty v-else description="暂无数据，请编辑流程添加节点"></el-empty>
      </div>
    </el-card>
    <!-- 弹窗：查询节点任务 -->
    <TaskDetail :id="dialogTaskDtl.id" :visible="dialogTaskDtl.visible" @dialogClose="closeDtlTask"></TaskDetail>
    <!-- 弹窗：审批 -->
    <!-- 工艺定价表单弹窗 -->
    <el-dialog v-model="dialogApprove.visible" :title="dialogApprove.title" width="500px" @close="closeApprove">
      <el-form ref="roleFormRef" :model="formData" label-width="100px" label-position="top">
        <el-form-item label="审批建议" prop="remark">
          <el-input type="textarea" :rows="3" v-model="formData.remark" placeholder="请输入审批建议" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmitApprove">确 定</el-button>
          <el-button @click="closeApprove">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { FLOW_AUDIT_TYPE_LABEL, FLOW_NODE_TYPE_LABEL, FlowNodeType } from "@/api/flow/flowNode.api";
import TaskDetail from "./components/taskDetail.vue";
import { FLOW_ACT_ROLE_LABEL, FLOW_CANDIDAT_TYPE_LABEL } from "@/api/flow/flowNodeTask.api";
import BuildAPI, { BuildApproveForm, ContractBuildStatus } from "@/api/flow/build.api";
import { decryptDES } from "@/utils/des";
import ActivityAPI from "@/api/flow/activity.api";
import { ActivityNodeVO } from "@/api/flow/activityNode.api";

const route = useRoute();

const id = ref(""); // 合同id
const name = ref(""); // 合同名称
const isAudit = ref(false); // 是否审核
const activityId = ref(""); //流程实例id
const activityInfo = ref(); //流程实例对象
const nodeList = ref<ActivityNodeVO[]>([]); //节点列表
// 审批表单
const formData = reactive<BuildApproveForm>({
  contractId: "",
  pass: false,
  remark: "",
});

const planLoading = ref(false);
const flowLoading = ref(false);

watch(
  () => route.query.key,
  async (val) => {
    // 提取转换密文对象
    const str = decryptDES(val as string);
    const busiInfo = JSON.parse(str) || {}; //业务信息
    id.value = busiInfo.id;
    name.value = busiInfo.name;
    isAudit.value = busiInfo.isAudit;
    formData.contractId = id.value;
    // 获取实例id和详情
    loadBase();
  },
  {
    immediate: true,
  }
);

// 加载基础信息
async function loadBase() {
  planLoading.value = true;
  try {
    const contractBuild = await BuildAPI.loadDetail(id.value);
    contractBuild.status != ContractBuildStatus.SUB_APPROVAL && (isAudit.value = false);
    activityId.value = contractBuild.activityId;
    activityId.value && loadFlowDetail();
  } catch (error) {
    console.log(error);
  }
  planLoading.value = false;
}

// 加载详情
const loadFlowDetail = () => {
  if (!activityId.value) {
    nodeList.value = [];
    return;
  }
  flowLoading.value = true;
  // 加载流程
  ActivityAPI.load(activityId.value)
    .then((data) => {
      activityInfo.value = data;
      nodeList.value = data.activityNodes;
    })
    .finally(() => {
      flowLoading.value = false;
    });
};

// 获取审核回退的节点
function getAuditBackName(node: ActivityNodeVO) {
  const backNode = nodeList.value.find((item) => item.id == node.backNodeId);
  return `审核方式：${FLOW_AUDIT_TYPE_LABEL[node.auditorType!]}，审核不通过回退至：${backNode?.name}`;
}

/**
 * 任务详情弹窗
 */
const dialogTaskDtl = reactive<{
  visible: boolean;
  id?: string;
}>({
  visible: false,
});

function handleDtlTask(id?: string) {
  dialogTaskDtl.visible = true;
  dialogTaskDtl.id = id;
}

function closeDtlTask() {
  dialogTaskDtl.visible = false;
}

/**
 * 审批弹窗
 */
const dialogApprove = reactive<{
  visible: boolean;
  title: string;
}>({
  visible: false,
  title: "",
});

function handleApprove(isPass: boolean) {
  dialogApprove.visible = true;
  dialogApprove.title = isPass ? "审批通过" : "审批驳回";
  formData.remark = isPass ? "审核通过" : "";
  formData.pass = isPass;
}

function closeApprove() {
  dialogApprove.visible = false;
}

function handleSubmitApprove() {
  if (!formData.remark) {
    ElMessage.warning("请填写审批建议");
    return;
  }
  BuildAPI.approval(formData)
    .then(() => {
      ElMessage.success("审批完成");
      closeApprove();
      loadBase();
    })
    .catch((error) => {
      console.error(error.message);
    });
}
</script>

<style lang="scss" scoped>
:deep(.el-card__body) {
  height: calc(100% - 70px);
}

.temp-item {
  border: 1px solid #eee;
  border-radius: 5px;
  padding: 10px 14px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.3s ease-in-out;

  p {
    padding-bottom: 3px;
  }

  span {
    font-size: 0.75em;
    color: #999;
  }

  &:hover {
    border-color: #ccc;
    box-shadow: 3px 3px 5px #ccc;
  }

  &.active {
    border-color: var(--el-color-primary);

    p {
      color: var(--el-color-primary);
      font-weight: bold;
    }

    span {
      color: #666;
    }
  }
}

.flow-node-wrap {
  display: flex;
  white-space: nowrap;
}

.flow-node {
  display: flex;
  width: 18em;
  flex-shrink: 0;
  margin-right: 16px;
  margin-bottom: 15px;
  flex-direction: column;
  font-size: 0.9em;

  .node-name {
    display: flex;
    align-items: center;
    padding: 5px 10px;
    margin-right: -20px;
    // background-color: var(--el-bg-color-page);
    background: url("data:image/svg+xml;charset=utf-8,%3Csvg t='1755228742853' class='icon' viewBox='0 0 1702 1024' version='1.1' xmlns='http://www.w3.org/2000/svg' p-id='15610' data-spm-anchor-id='a313x.search_index.0.i8.6e8f3a81r1hw4J' width='60' height='60'%3E%3Cpath d='M1701.385 541.177l-230.083-234.545H0l216.77 233.967L0 776.004h1471.302z' p-id='15611' data-spm-anchor-id='a313x.search_index.0.i7.6e8f3a81r1hw4J' class='' fill='%23d9e6ff'%3E%3C/path%3E%3C/svg%3E") no-repeat right 52% / 105% auto;
    margin-bottom: 7px;

    .node-index {
      font-size: 1.6em;
      font-weight: bold;
      color: #fff;
      text-shadow: 1px 1px 4px #999;
    }

    .node-remark {
      font-size: 0.75em;
      color: #aaa;
      white-space: nowrap;
      /* 防止文本换行 */
      overflow: hidden;
      /* 隐藏超出部分的文本 */
      text-overflow: ellipsis;
      /* 显示省略号 */
    }

    .node-tag {
      background: none;
    }
  }

  .node-tasks {
    flex: 1;
    padding: 12px 7px 5px;
    background-color: #f3f4fb;
    border-radius: 7px;

    .task-line {
      padding: 5px 10px;
      background-color: #fff;
      border-radius: 9px;
      margin-bottom: 9px;

      .task-title {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .role-icon {
          display: flex;
          align-items: center;
          color: #999;
          font-size: 0.8em;
        }
      }

      .task-remark {
        font-size: 0.75em;
        margin-top: 5px;
        white-space: nowrap;
        /* 防止文本换行 */
        overflow: hidden;
        /* 隐藏超出部分的文本 */
        text-overflow: ellipsis;
        /* 显示省略号 */
      }
    }
  }
}

/* 添加按钮 */
.flow-add-button {
  border: 1px dashed #d1d1d1;
  border-radius: 5px;
  padding: 15px;
  background-color: #fff;
  border-radius: 9px;
  margin-bottom: 9px;
  font-weight: bold;
  cursor: pointer;
  color: #9e9e9e;
  transition: all 0.3s ease-in-out;

  &:hover {
    border-color: var(--el-color-primary);
    color: var(--el-color-primary);
  }
}
</style>
